package com.practice.java.practice4Mybatis.service;

import com.practice.java.practice4Mybatis.MybatisSqlSessionFactory;
import com.practice.java.practice4Mybatis.domain.Student;
import com.practice.java.practice4Mybatis.mapper.StudentMapper;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class StudentService {

    private final Logger logger = LoggerFactory.getLogger(StudentService.class);

    public List<Student> findAllStudents() {
        SqlSession sqlSession = MybatisSqlSessionFactory.openSession();
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            return studentMapper.findAllStudents();
        } finally {
            sqlSession.close();
        }
    }

    public Student findStudentById(int studId) {
        logger.debug("findStudentById:{}", studId);
        SqlSession sqlSession = MybatisSqlSessionFactory.openSession();
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            return studentMapper.findStudentById(studId);
        } finally {
            sqlSession.close();
        }
    }

    public int insertStudent(Student student) {
        logger.debug("insertStudent:{}", student);
        SqlSession sqlSession = MybatisSqlSessionFactory.openSession();
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            int i = studentMapper.insertStudent(student);
            sqlSession.commit();
            logger.debug("insertStudent result:{} {}",i,student);
            return i;
        } finally {
            sqlSession.close();
        }
    }

}
